<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use App\Controller\BaseController;
use App\Model\User as UserModel;
use Hyperf\Context\ApplicationContext;

use GuzzleHttp\Client;

#[AutoController]
class LoginController extends BaseController
{
	private $request;

	private Client $httpClient;

	protected $redis;

	public function __construct(Client $httpClient)
	{
		$this->httpClient = $httpClient;
		$container = ApplicationContext::getContainer();
		$this->redis = $container->get(\Hyperf\Redis\Redis::class);
	}

	/**
	 * 是否登录
	 */
	public function isLogin(RequestInterface $request)
	{
		return $this->Auth($request);
	}

	/**
	 * 账号登录页面
	 */
	public function index(RequestInterface $request)
	{
		$data = $request->query();
		$formData = json_decode($data['formdata'], true);
		if (!empty($formData['username']) && !empty($formData['password'])) {
			$res = UserModel::login($formData);
		} else {
			$res['err'] = 1;
			$res['msg'] = "登录失败，账号/密码为空";
		}

		return json_encode($res);
	}

	/**
	 * 账号注册页面
	 */
	public function register(RequestInterface $request)
	{
		$data = $request->query();
		$formData = json_decode($data['formdata'], true);
		if (!empty($formData['username']) && !empty($formData['password'])) {
			$res = UserModel::register($formData);
		} else {
			$res['err'] = 1;
			$res['msg'] = "登录失败，账号/密码为空";
		}
		return json_encode($res);
	}

	/**
	 * 微信登录页面
	 */
	public function wxlogin(RequestInterface $request)
	{
		$data = $request->post();
		$err = 1;
		$msg = "登录失败，请重试..";
		$id = '';
		$nickname = '';
		$username = '';
		$avatar = '';
		$token = '';
		if (!empty($data['code']) && is_string($data['code'])) {
			$nacos = \App\Library\Nacos::getInstance();
			$config = $nacos->getConfig('appidAndAppsecret', 'DEFAULT_GROUP');
			$url = 'https://api.weixin.qq.com/sns/jscode2session';
			$data = [
				'appid' => $config['appid'],
				'secret' => $config['secret'],
				'grant_type' => $config['grant_type'],
				'js_code' => $data['code']
			];

			$response = $this->httpClient->request('GET', $url, ['query' => $data]);
			if ($response->getStatusCode() === 200) {
				$responseData = $response->getBody()->getContents();
				$jsonData = json_decode($responseData, true);
				$userInfo = UserModel::where('openid', $jsonData['openid'])->first();
				$time = time();
				if (empty($userInfo)) {
					$user = new UserModel();
					$getUserName = $time . $user->id;
					$getNickName = '用户' . $time . $user->id;
					$getToken = UserModel::generateToken($user->id, $time);
					$user->openid = $jsonData['openid'];
					$user->session_key = $jsonData['session_key'];
					$user->unionid = $jsonData['unionid'];
					$user->username = $getUserName;
					$user->nickname = $getNickName;
					$user->token = $getToken;
					$user->expiration_at = $time + 60 * 60 * 24;
					$result = $user->save();
					if ($result) {
						$redisRes = $this->redis->set(strval($user->id), 0);
						if ($redisRes) {
							$err = 0;
							$msg = "登录成功";
							$id = $user->id;
							$nickname = $getNickName;
							$username = $getUserName;
							$avatar = '';
							$token = $getToken;
						} else {
							$msg = '登录失败，请重试..';
						}
					} else {
						$msg = '登录失败，请重试...';
					}
				} else {
					$err = 0;
					$msg = "登录成功";
					$id = $userInfo->id;
					$nickname = $userInfo->nickname;
					$username = $userInfo->username;
					$avatar = $userInfo->avatar;
					$token = $userInfo->token;
					$user = UserModel::query()->find($id);
					$user->expiration_at = $time + 60 * 60 * 24;
					$user->save();
				}
			} else {
				var_dump("请求失败，状态码: " . $response->getStatusCode());
			}
		}
		$arr['err'] = $err;
		$arr['msg'] = $msg;
		$arr['data']['id'] = $id;
		$arr['data']['nickname'] = $nickname;
		$arr['data']['username'] = $username;
		$arr['data']['avatar'] = $avatar;
		$arr['data']['token'] = $token;
		return json_encode($arr);
	}

	/**
	 * 微信授权获取个人信息
	 */
	public function wxaccredit(RequestInterface $request)
	{
		$isAuth = $this->Auth($request, 1);
		$AuthInfo = json_decode($isAuth, true);
		if ($AuthInfo['err'] === 0) {
			$data = $request->post();

			// 参数存在性检查
			if (empty($data['nickName']) || empty($data['avatarUrl']) || empty($data['userid'])) {
				$res['err'] = 1;
				$res['msg'] = "授权失败，缺少参数";
				return json_encode($res);
			}

			// 过滤参数
			$nickName = filter_var($data['nickName'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
			$avatarUrl = filter_var($data['avatarUrl'], FILTER_SANITIZE_URL);
			$userid = filter_var($data['userid'], FILTER_SANITIZE_NUMBER_INT);
			if ($nickName === false || $avatarUrl === false || $userid === false) {
				$res['err'] = 1;
				$res['msg'] = "授权失败，参数错误";
				return json_encode($res);
			}

			// 长度验证
			if (strlen($nickName) > 50 || strlen($avatarUrl) > 255) {
				$res['err'] = 1;
				$res['msg'] = "授权失败，参数长度超过限制";
				return json_encode($res);
			}

			$userInfo = UserModel::where('id', $userid)->get();
			if (!empty($userInfo)) {
				$result = UserModel::where('id', $userid)->update(['wx_nickname' => $nickName, 'wx_avatar' => $avatarUrl]);
				if (!$result) {
					$res['err'] = 1;
					$res['msg'] = "授权失败，请重新授权";
				}
			}
			$res['err'] = 0;
			$res['msg'] = "授权成功";
		} else {
			$res['err'] = 1;
			$res['msg'] = "认证失败，请重新授权";
		}
		return json_encode($res);
	}

	/**
	 * 微信登录页面（仅测试使用）
	 */
	public function wxloginTest(RequestInterface $request)
	{
		//    	   $data = $request->post();
		$err = 1;
		$msg = "登录失败，请重试..";
		$id = '';
		$nickname = '';
		$username = '';
		$avatar = '';
		$token = '';
		//    	   if(!empty($data['code']) && is_string($data['code'])){
		//    	   	   $nacos = \App\Library\Nacos::getInstance();
		//		   $config = $nacos->getConfig('appidAndAppsecret','DEFAULT_GROUP');
		//	        $url = 'https://api.weixin.qq.com/sns/jscode2session';
		//	        $data = [
		//			  'appid' => $config['appid'],
		//                 'secret' => $config['secret'],
		//                 'grant_type' => $config['grant_type'],
		//                 'js_code' => $data['code']
		//	        ];

		//	        $response = $this->httpClient->request('GET', $url, ['query' => $data]);	   
		//	        if ($response->getStatusCode() === 200) {
		//	            $responseData = $response->getBody()->getContents();
		//	            $jsonData = json_decode($responseData, true);
		$userInfo = UserModel::where('openid', 'oPKC94oEx2RitsfC_NWrtkunwfUY')->first();
		$time = time();
		if (empty($userInfo)) {
			$user = new UserModel();
			$getUserName = $time . $user->id;
			$getNickName = '用户' . $time . $user->id;
			$getToken = UserModel::generateToken($user->id, $time);
			$user->openid = $jsonData['openid'];
			$user->session_key = $jsonData['session_key'];
			$user->unionid = $jsonData['unionid'];
			$user->username = $getUserName;
			$user->nickname = $getNickName;
			$user->token = $getToken;
			$user->expiration_at = $time + 60 * 60 * 24;
			$result = $user->save();
			if ($result) {
				$redisRes = $this->redis->set(strval($user->id), 0);
				if ($redisRes) {
					$err = 0;
					$msg = "登录成功";
					$id = $user->id;
					$nickname = $getNickName;
					$username = $getUserName;
					$avatar = '';
					$token = $getToken;
				} else {
					$msg = '登录失败，请重试..';
				}
			} else {
				$msg = '登录失败，请重试...';
			}
		} else {
			$err = 0;
			$msg = "登录成功";
			$id = $userInfo->id;
			$nickname = $userInfo->nickname;
			$username = $userInfo->username;
			$avatar = $userInfo->avatar;
			$token = $userInfo->token;
			$user = UserModel::query()->find($id);
			$user->expiration_at = $time + 60 * 60 * 24;
			$user->save();
		}
		//	        } else {
		//	        		var_dump("请求失败，状态码: " . $response->getStatusCode());
		//	        }   
		//    	   }
		$arr['err'] = $err;
		$arr['msg'] = $msg;
		$arr['data']['id'] = $id;
		$arr['data']['nickname'] = $nickname;
		$arr['data']['username'] = $username;
		$arr['data']['avatar'] = $avatar;
		$arr['data']['token'] = $token;
		return json_encode($arr);
	}
}
